package com.swinw.asumall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.swinw.asumall.ware.feign.ProductFeignService;
import com.swinw.asumall.ware.vo.SkuIdAndCountVo;
import com.swinw.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swinw.common.utils.PageUtils;
import com.swinw.common.utils.Query;

import com.swinw.asumall.ware.dao.WareSkuDao;
import com.swinw.asumall.ware.entity.WareSkuEntity;
import com.swinw.asumall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    /**
     *  skuId: 3
     *  wareId: 3
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            try{
                int i = Integer.parseInt(skuId);
                queryWrapper.eq("sku_id",i);
            }catch (Exception e){

            }
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            try{
                int i = Integer.parseInt(wareId);
                queryWrapper.eq("ware_id",i);
            }catch (Exception e){

            }
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断仓库中是否存在当前的商品库存，如果存在就修改，不存在就添加
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id",skuId)
                .eq("ware_id",wareId);
        List<WareSkuEntity> list = this.list(queryWrapper);
        if(list == null || list.size() == 0){//标示当前的商品没有库存
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                skuEntity.setSkuName((String) data.get("skuName"));

            }catch (Exception e){

            }

            baseMapper.insert(skuEntity);
        }else{
            baseMapper.updateWareSkuNum(skuId,wareId,skuNum);
        }
    }

    @Override
    public WareSkuEntity selectByWareBySkuId(Long skuId) {
        WareSkuEntity entity =  this.baseMapper.selectBySkuId(skuId);
        return entity;
    }

    /**
     * 锁库存操作
     * @param skuAndCount
     * @return
     */
    @Transactional
    @Override
    public R lockWare(String skuAndCount) throws Exception {
        String[] split = skuAndCount.split(";");
        for (int i = 0; i < split.length; i++) {
            String[] ss = split[i].split("-");
            Long skuId = Long.parseLong(ss[0]);
            Integer count = Integer.parseInt(ss[1]);

            //1、查询当前的skuId在那些仓库有库存
            List<WareSkuEntity> list = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId));

            //2、锁库存
            for (WareSkuEntity entity : list) {
                int wareCount = entity.getStock() - entity.getStockLocked();
                if(wareCount >= count){//当前仓库的库存可以支付当前的订单
                    entity.setStockLocked(entity.getStockLocked()+count);
                    baseMapper.update(entity,new UpdateWrapper<WareSkuEntity>()
                            .eq("sku_id",skuId)
                            .eq("ware_id",entity.getWareId()));
                    count = 0;
                }else{
                    int newCount = count - wareCount;
                    count = count - newCount;//剩下的数量
                    entity.setStockLocked(entity.getStockLocked()+newCount);
                    baseMapper.update(entity,new UpdateWrapper<WareSkuEntity>()
                            .eq("sku_id",skuId)
                            .eq("ware_id",entity.getWareId()));
                }
            }
            if(count > 0){//库存不足
                int kgfkjhfgkjhg = 10/0;
            }
        }
        return R.ok();
    }

}